package com.example.bookstore.web;

import com.example.bookstore.pojo.User;
import com.example.bookstore.service.UserService;
import com.example.bookstore.service.impl.UserServiceImpl;
import com.example.bookstore.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    //post请求先找此处的doPost()，找不到去找父类的doPost()


//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //获取隐藏域请求，登录为"login"，注册为"register"
//        String action = req.getParameter("action");
//
////        if ("login".equals(action)) {
////            //处理登录
////            login(req, resp);
////
////        } else if ("register".equals(action)) {
////            //处理注册
////            register(req,resp);
////        }
//
//        //利用反射调用方法
//        try {
//            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            method.invoke(this,req,resp);
//
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }



    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user =  WebUtils.copyParamToBean(req.getParameterMap(),new User());

        try {
            User login = userService.login(user);
            if (login == null) {
                //回显表单项信息
                req.setAttribute("msg", "用户名或密码错误");
                req.setAttribute("username", username);

                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
                System.out.println("用户" + username + "登录失败");


            } else {
                Cookie cookie = new Cookie("username", "test");
                cookie.setMaxAge(1200);
                resp.addCookie(cookie);



                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
                System.out.println("用户" + username + "登录成功");

//                System.out.println("cookie 111 success");


            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
//            System.out.println(code);

        User user =  WebUtils.copyParamToBean(req.getParameterMap(),new User());

        if (((String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY)).equalsIgnoreCase(code)) {
            try {
                if (!userService.existUsername(username)) {
                    userService.registerUser(user);
                    req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
                    System.out.println("用户" + username + "注册成功");
                    req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
                } else {//用户名已存在
                    System.out.println("用户" + username + "尝试注册，但用户名已存在");
                    //显示回显信息
                    req.setAttribute("msg", "用户名已存在");
                    req.setAttribute("username", username);
                    req.setAttribute("email", email);

                    req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {//验证码不正确
            System.out.println("验证码错误,用户输入的验证码为：" + code + "\t实际为bnbnb");
            //显示回显信息
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", username);
            req.setAttribute("email", email);

            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}
